package com.vn.toaa.karaoke.database;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Comment;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.vn.toaa.karaoke.ui.Constant;

public class FavoriteDatasouce {
	
	public static final String COL_ID = "Id";
	public static final String COL_TYPE = "Type";
	public static final String[] ALL_COLUMNS = {
		COL_ID,
		COL_TYPE
	};
	private SQLiteDatabase mDatabase;
	
	public void open() {
		ExternalSQLiteHelper.getInstance().openDatabase();
		mDatabase = ExternalSQLiteHelper.getInstance().getDatabase();
	}
	
	public void close() {
		ExternalSQLiteHelper.getInstance().closeDataBase();
	}
	
	public boolean isSongExisted(int songId) {
		if (!mDatabase.isOpen()) {
			open();
		}
		boolean result = false;
		try {
			final String whereClause = String.format("%s = %d", COL_ID, songId);
			Cursor cursor = mDatabase.query(Constant.TABLE_FAVOURITE, null, whereClause, null, null, null, null);
			if (cursor.getCount() > 0) {
				result = true;
			}
			cursor.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public List<Integer> selectAllSongs() {
		List<Integer> result = new ArrayList<Integer>();
		if (!mDatabase.isOpen()) {
			open();
		}
		try {
			Cursor cursor = mDatabase.query(Constant.TABLE_FAVOURITE, new String[] { COL_ID }, null, null, null, null,
					null);
			if (cursor.getCount() > 0) {
				cursor.moveToFirst();
				while (!cursor.isAfterLast()) {
					result.add(cursor.getInt(0));
					cursor.moveToNext();
				}
			}
			cursor.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public void deleteFavoriteSongByID(int songId) {
		if (!mDatabase.isOpen()) {
			open();
		}
		try {
		    mDatabase.beginTransaction();
			final String whereClause = String.format("%s = %d", COL_ID, songId);
			mDatabase.delete(Constant.TABLE_FAVOURITE, whereClause, null);
		    mDatabase.setTransactionSuccessful();
		} catch(SQLException e) {
			e.printStackTrace();
		} finally {
		   mDatabase.endTransaction();
		}
	}
	
	public void insertFavoriteSong(int songId) {
		ContentValues values = new ContentValues();
		values.put(COL_ID, songId);
		values.put(COL_TYPE, 0);
		try {
			mDatabase.beginTransaction();
			mDatabase.insert(Constant.TABLE_FAVOURITE, null, values);
			mDatabase.setTransactionSuccessful();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			mDatabase.endTransaction();
		}
	}

	private FavoriteModel cursorToModel(Cursor cursor) {
		return new FavoriteModel(cursor.getInt(0), cursor.getInt(1));
	}
	

}
